const ffi=require("ffi");
const path=require("path");
const iconv = require("iconv-lite");


function IdCard(){

    var libpath;
    if(process.env.NODE_ENV === 'production'){
        libpath="termb.dll"
    }else{
        libpath=path.join(__dirname, '/termb.dll');
    }
    this.testLib= ffi.Library(libpath, {
        //初始化设备(串口:1-16,USB:1001-1016)
        InitComm:['int',['int']],
        //关闭设备,成功返回1
        CloseComm:['int',[]],
        //读卡验证
        Authenticate:['int',[]],
        //读取身份证信息,参数是整数,1读基本信息；3表示读追加地址;7读指纹证信息
        Read_Content:['int',['int']],
        GetPeopleName:['int',['string','int']],
        GetPeopleAddress:['int',['string','int']],
        GetPeopleIDCode:['int',['string','int']],
        GetPeopleBirthday:['int',['string','int']],
        GetPeopleNation:['int',['string','int']],
        GetPeopleSex:['int',['string','int']],
        GetDepartment:['int',['string','int']],
        GetStartDate:['int',['string','int']],
        GetEndDate:['int',['string','int']],
        GetPhotoBMP:['int',['string','int']]
    });
    this.readInfo=function(){
        //初始化设备
        var dllRet = this.testLib.InitComm(1001);
        if(dllRet<0){
            this.testLib.CloseComm();
            console.log("初始化设备失败=>"+dllRet);
            return "初始化设备失败=>"+dllRet
        }
        console.log("初始化设备成功");
        //读卡验证
        this.testLib.Authenticate();

        // //读基本信息
        var readResult=this.testLib.Read_Content(1);
        //读卡完毕后，关闭设备
        this.testLib.CloseComm();
        if(readResult!=1){
            console.log("读基本信息失败=>"+readResult);
            return "读基本信息失败=>"+readResult;
        }
        console.log(`读基本信息成功`);
        var name=this.getIdCardString("GetPeopleName",31);
        var address=this.getIdCardString("GetPeopleAddress",71);
        var idCard=this.getIdCardString("GetPeopleIDCode",19);
        var birthday=this.getIdCardString("GetPeopleBirthday",9);
        var nation=this.getIdCardString("GetPeopleNation",8);
        var sex=this.getIdCardString("GetPeopleSex",6);
        var department=this.getIdCardString("GetDepartment",31);//发证机关
        var startDate=this.getIdCardString("GetStartDate",9);//证件开始日期
        var endDate=this.getIdCardString("GetEndDate",9);//证件结束日期
        var photoBMP=this.getPhotoBMP("GetPhotoBMP");//照片
        return {
            name,address,idCard,birthday,nation,sex,department,startDate,endDate,photoBMP
        }
    }
    this.getIdCardString=function(string,len){
        var buffer= Buffer.alloc(len);
        var resultRen=this.testLib[string](buffer,len);
        var newBuf=Buffer.alloc(resultRen);
        buffer.copy(newBuf, 0, 0, resultRen);
        return  iconv.decode(newBuf, 'GBK');
    }
    this.getPhotoBMP=function(string){
        var buffer= Buffer.alloc(50000);
        var resultRen=this.testLib[string](buffer,50000);
        return buffer.toString("base64",0,resultRen);
    }

}

exports.IdCard=new IdCard();





